import {useEffect, useState} from "react";
import {useAuth} from "./AuthContext.jsx";

export default function Invite({getEvent,event}) {


    const [searchedUsers, setSearchedUsers] = useState([])
    const [isInviting, setIsInviting] = useState(false)
    const [searchString, setSearchString] = useState('')
    const {authInfo} = useAuth()

    useEffect(()=>{
        getSearchedUsers()
    },[searchString])

    useEffect(()=>{
        // Do Something here
    },[event])

    async function getSearchedUsers(){
        if(searchString.trim()==="") return;
        const res = await fetch(`http://127.0.0.1:8000/api/v1/users?s=${searchString}&inviting_to=${event.id}`,{
            method: "get",
            headers: {
                "X-Request-ID": authInfo ? authInfo.token_uuid : "",
                "Authorization": authInfo ? `Bearer ${authInfo.token}` : "",
            }

        })
        if(res.status===200){
            const data = (await res.json()).data
            setSearchedUsers(data.users)
        }
    }

    async function handleAddInvitation(user_id,e){
        console.log(e)
        const res = await fetch("http://127.0.0.1:8000/api/v1/events/invite",{
            method: "post",
            headers: {
                "X-Request-ID": authInfo ? authInfo.token_uuid : "",
                "Authorization": authInfo ? `Bearer ${authInfo.token}` : "",
                "Content-Type": "application/json"
            },
            body: JSON.stringify({
                event_id: event.id,
                user_id,
            })

        });
        if(res.status===201) {
            setSearchString("");
            setIsInviting(false)
            await getEvent()
            //console.table(event.invited_users)
        }
        //console.log(res.status)

    }

    async function cancelInvitation(user_id,e){
        console.log("UserId:",user_id)
        const res = await fetch("http://127.0.0.1:8000/api/v1/invitations",{
            method: "delete",
            headers: {
                "X-Request-ID": authInfo ? authInfo.token_uuid : "",
                "Authorization": authInfo ? `Bearer ${authInfo.token}` : "",
                "Content-Type": "application/json"
            },
            body: JSON.stringify({
                event_id: event.id,
                user_id
            })
        });
        if(res.status===200){
            console.log((await res.json()))
            await getEvent()
        }
        else{
            alert("Invitation canceling failed: "+res.status)
        }
    }

    return (
        <>
            {event?.can_invite && authInfo && (
                <button
                    id="invite-btn"
                    className="bg-green-500 text-white px-4 py-2 rounded hover:bg-green-600 mb-2"
                    onClick={()=>setIsInviting(true)}
                >
                    Invite
                </button>
            )}
            <div id="invite-form" className={isInviting? "": "hidden" +" mt-2 p-4 bg-gray-100 rounded relative"}>
                <input
                    onChange={e=>setSearchString(e.target.value)}
                    value={searchString}
                    id="user-search"
                    type="search"
                    className="w-full p-2 border rounded mb-2"
                    placeholder="Search users..."
                    autoComplete="off"
                />
                <div
                    id="user-dropdown"
                    className={searchString.length>0? "":"hidden"+" absolute left-0 right-0 bg-white border rounded shadow-md max-h-40 overflow-y-auto"}
                >
                    {searchedUsers.map(u=> (
                        <div
                            key={u.id}
                            onDoubleClick={(e)=>handleAddInvitation(u.id,e)}
                            className="p-2 hover:bg-gray-100 cursor-pointer select-none">{u.name} ({u.email})</div>
                    ))}

                </div>
            </div>
            {authInfo && event?.type === "PRIVATE" && (
                <p className="text-lg font-semibold text-gray-800 mt-2">
                    Invited: <span id="invited-list" className="flex flex-wrap gap-2">
                            <span className="invited-user bg-gray-200 px-2 py-1 rounded flex items-center">
                                {event?.invited_users?.map(iu=>(
                                    <label className="mr-4" key={iu.email}>
                                    <span>{iu.email}</span>
                                {event?.can_invite && (
                                    <span
                                        onClick={e=>cancelInvitation(iu.id,e)}
                                        className="ml-1 text-red-500 cursor-pointer">x</span>
                                    )}
                                    </label>
                                ))}

                            </span>
                        </span>
                </p>
            )}
        </>
    )
}